package com.zx.yixun.ui

import android.graphics.Color
import android.os.Bundle
import android.os.Power
import android.util.Log
import androidx.appcompat.widget.Toolbar
import com.blankj.utilcode.util.ToastUtils
import com.hd.serialport.listener.SerialPortMeasureListener
import com.hd.serialport.method.DeviceMeasureController
import com.hd.serialport.param.SerialPortMeasureParameter
import com.hd.serialport.utils.HexDump
import com.hd.serialport.utils.L
import com.zx.yixun.R
import com.zx.yixun.util.MyUtils
import com.zx.ymy.base.BaseActivity
import kotlinx.android.synthetic.main.activity_esop.*
import java.io.OutputStream
import java.util.*
import java.util.concurrent.locks.ReentrantLock

class EsopActivity :BaseActivity() {

    private var outputIO: OutputStream? = null
    @Volatile
    var isChuliao=1//1查询出料 2不查询 3 查询入料

    override fun getToolbar(): Toolbar? {
       return null
    }

    override fun getContentId(): Int {
        return R.layout.activity_esop
    }

    override fun onContentCreate(savedInstanceState: Bundle?) {
        startConnect()
        btn_qlwc.setOnClickListener {
            //取料完成
            isChuliao=2
            sendData("01 05 00 08 00 01 8D C8")
            sendData("01 05 00 12 00 01 " + MyUtils.getCRC(MyUtils.decodeHexString("010500120001")))
        }

        btn_zbcl.setOnClickListener {
            //准备出料
            isChuliao=3
            sendData("01 05 00 06 00 01 EC 0B")
            sendData("01 01 00 03 00 01 0D CA")
        }

        btn_clwc.setOnClickListener {
            //出料完成
            isChuliao=1
            sendData("01 05 00 07 00 01 BD CB")
            sendData("01 05 00 10 00 01 " + MyUtils.getCRC(MyUtils.decodeHexString("010500100001")))
        }

        tv_photo.setOnClickListener {
            tv_photo.setBackgroundResource(R.drawable.shape_btn_left_select)
            tv_video.setBackgroundResource(R.drawable.shape_btn_right_normal)
            tv_photo.setTextColor(Color.parseColor("#FFFFFF"))
            tv_video.setTextColor(Color.parseColor("#0090D9"))
        }

        tv_video.setOnClickListener {
            tv_photo.setBackgroundResource(R.drawable.shape_btn_left_normal)
            tv_video.setBackgroundResource(R.drawable.shape_btn_right_select)
            tv_photo.setTextColor(Color.parseColor("#0090D9"))
            tv_video.setTextColor(Color.parseColor("#FFFFFF"))
        }

        WriteSerialPortThread().start()
    }


    protected fun startConnect() {
        DeviceMeasureController.measure(serialPortMeasureParameter = SerialPortMeasureParameter(
            "dev/ttyUSB0",
            baudRate = 115200,
            flags = 0
        ),
            serialPortMeasureListener = object : SerialPortMeasureListener {
                override fun measureError(message: String) {
                    ToastUtils.showShort(message)
                }

                override fun measuring(path: String, data: ByteArray) {
                    receiveData(data)
                }

                override fun write(outputStream: OutputStream) {
                    outputIO = outputStream
                }
            })
    }

    protected fun receiveData(data: ByteArray) {
        L.d("==" + Arrays.toString(data))
        val result = HexDump.toHexString(data)
        if (isChuliao==1){
            //查询出料中
            if (!result.contains("01010100")&&!result.contains("01010101")){
                return
            }
            val state: String = result.substring(6, 8)
            runOnUiThread {
                if (state=="01"){
                    tv_state.text="可以出料"
                }else{
                    tv_state.text="不可以出料"
                }
            }
        }else if (isChuliao==3){
            //查询入料中
            if (!result.contains("01010100")&&!result.contains("01010101")){
                return
            }
            val state: String = result.substring(6, 8)
            runOnUiThread {
                if (state=="01"){
                    tv_state.text="可以入料"
                }else{
                    tv_state.text="不可以入料"
                }
            }
        }
        Log.e("receive", result)
    }


    protected fun writeData(arrayList: ArrayList<ByteArray>){
        arrayList.forEach { outputIO!!.write(it) }
        mLock.unlock()
    }

    var mLock=ReentrantLock()

    open fun sendData(data: String){
        mLock.lock()
        val arrayList = ArrayList<ByteArray>()
        val ins = data.trim()
        Log.e("send", ins)
        sendHexData(ins, arrayList)
    }


    private fun sendHexData(ins: String, arrayList: ArrayList<ByteArray>) {
        val hexs = ins.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        val bytes = ByteArray(hexs.size)
        var okflag = true
        for (index in hexs.indices) {
            val hex = hexs[index]
            try {
                val d = Integer.parseInt(hex, 16)
                bytes[index] = d.toByte()
            } catch (e: NumberFormatException) {
                e.printStackTrace()
            }
        }
        arrayList.add(bytes)
        if (okflag && arrayList.size > 0) {
            writeData(arrayList)
        }
    }


    // 读取数据
    inner class WriteSerialPortThread : Thread() {
        override fun run() {
            while (true) {
                try {
                    if (this@EsopActivity.isChuliao==1){
                        this@EsopActivity.sendData("01 01 00 02 00 01 5C 0A")
                    }else if(this@EsopActivity.isChuliao==3){
                        this@EsopActivity.sendData("01 01 00 03 00 01 0D CA")
                    }
                    sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }
    }


}